<template>
  <form-wrap :rules="rules" :schema="formSchema" @register="formRegister" />
</template>
<script setup lang="ts">
  import { listValidTreeNodeApi as listOrgTreeNodeApi } from '@/api/system/organization';
  import { listAllApi as listRoleApi } from '@/api/system/role';
  import { getApi } from '@/api/system/user';
  import { useForm } from '@/hooks/form';
  import { useValidator } from '@/hooks/validator';

  const props = defineProps({
    userId: {
      type: String,
      default: () => null,
    },
  });

  const { required, checkUsername, checkEmail, checkMobile } = useValidator();
  const { formRegister, formMethods } = useForm();
  const { setValues, submitForm } = formMethods;

  const formSchema = ref<FormSchema[]>([
    { field: 'id', hidden: true },
    {
      field: 'username',
      label: '用户名',
      type: 'Input',
      props: { maxlength: 30 },
    },
    {
      field: 'realName',
      label: '真实姓名',
      type: 'Input',
      props: { maxlength: 30 },
    },
    {
      field: 'gender',
      label: '性别',
      type: 'Select',
      enumName: 'Gender',
    },
    {
      field: 'mobile',
      label: '移动电话',
      type: 'Input',
      props: {
        maxlength: 11,
      },
    },
    {
      field: 'email',
      label: '电子邮件',
      type: 'Input',
      props: {
        maxlength: 100,
      },
    },
    {
      field: 'orgId',
      label: '所属组织',
      type: 'a-tree-select',
      props: {
        fieldNames: {
          key: 'id',
          title: 'name',
        },
        style: 'width: 100%;',
      },
      effect: {
        fetch: {
          action: async () => {
            return listOrgTreeNodeApi();
          },
          to: 'props.data',
        },
      },
    },
    {
      field: 'state',
      label: '启用状态',
      type: 'Select',
      enumName: 'State',
    },
    {
      field: 'roles',
      label: '角色',
      type: 'Select',
      props: {
        multiple: true,
        fieldNames: {
          label: 'name',
          value: 'id',
        },
      },
      effect: {
        fetch: {
          action: async () => {
            return listRoleApi();
          },
          to: 'options',
        },
      },
    },
  ]);

  const rules = reactive({
    username: [required(), checkUsername()],
    realName: [required()],
    gender: [required()],
    mobile: [checkMobile()],
    email: [checkEmail()],
    orgId: [required()],
    state: [required()],
  });

  const submit = async () => {
    return await submitForm();
  };

  watch(
    () => props.userId,
    async (userId) => {
      const res = await getApi(userId);
      setValues(res);
    },
    {
      deep: true,
      immediate: true,
    }
  );

  defineExpose({
    submit,
  });
</script>
